#!/bin/sh

# Note this is replaced by make install, not configure!
export MX_MODULE_DIR=@mx_module_dir@

set -e

if test ! -d ${MX_MODULE_DIR}; then
    echo "Something bad happened with the install script"
    echo "MX_DIR isn't pointing to a valid directory"
    exit 
fi

#process arguments
for arg in "$@"; do
    case $arg in
	"--passive")
	    PASSIVE=1
	    ;;
	"--manual")
	    MANUAL=1
	    ;;
	"--module")
	    MODULE=1
	    ;;
    esac
done

#create the files /etc/mx_mapper/{passive,mapper} if specified.
if test ! -d "/etc/mx_mapper"; then
    echo "/etc/mx_mapper didn't exist.  Creating it."
    mkdir /etc/mx_mapper && chmod 655 /etc/mx_mapper
fi
if [ "$PASSIVE" ]; then
    echo "Configuring a passive mapper"
    touch /etc/mx_mapper/passive && chmod 644 /etc/mx_mapper/passive
else
    rm -f /etc/mx_mapper/passive
fi
if [ "$MANUAL" ]; then
    echo "Configuring a manual mapper"
    echo "Mapper will not be started automatically!"
    touch /etc/mx_mapper/manual && chmod 644 /etc/mx_mapper/manual
else
    rm -f /etc/mx_mapper/manual
fi

echo "Creating mx devices"
$MX_MODULE_DIR/mx_create_devs

if test -d "/etc/init.d/"; then
    echo "Installing init script"
    cp ${MX_MODULE_DIR}/mx_start_stop /etc/init.d/mx
fi

if test -d "/etc/udev/rules.d/"; then
 cat <<EOF > /etc/udev/rules.d/10-mx.rules
# Myricom MX device rules
# ignore_remove introduced in 046, no effect before 
KERNEL="mxp[0-9]*",	NAME{ignore_remove}="%k", MODE="0600"
KERNEL="mx[0-9]*",	NAME{ignore_remove}="%k", MODE="0666"
EOF
fi

for module in gm mx_driver mx_mcp ; do 
 if [ -r /etc/hotplug/blacklist ]  &&
       ! grep -q "$module\$" /etc/hotplug/blacklist 2> /dev/null ; then
    echo -e "# Myri autoloading not supported yet\n$module" >> /etc/hotplug/blacklist
 fi
done

if test -d "/etc/dev.d"; then
  mkdir -p /etc/dev.d/mx 
  cat <<EOF > /etc/dev.d/mx/10-mx_mapper.dev
#!/bin/sh
# Myricom MX device creation callback
test "\$ACTION" = add || exit 0
# Myricom MX start mapper on device creation
case "\$DEVPATH" in
 /class/mx/mxp*)
   n=\`expr \$DEVPATH : '/class/mx/mxp\(.*\)'\`
   $MX_MODULE_DIR/mx_start_mapper \$n;;
esac
EOF
 chmod 755 /etc/dev.d/mx/10-mx_mapper.dev
fi
   
if test -d "/etc/modprobe.d"; then
  cat <<EOF > /etc/modprobe.d/mx
options mx_driver mx_mapper_path=$MX_MODULE_DIR/mx_start_mapper
remove mx_driver $MX_MODULE_DIR/mx_stop_mapper;modprobe -r --ignore-remove mx_driver && modprobe -r mx_mcp
blacklist mx_driver
EOF
fi

if test -n "$MODULE"; then
  driver_dir="/lib/modules/`uname -r`/mx"
  mkdir -p $driver_dir
  cp $MX_MODULE_DIR/mx_driver.ko $MX_MODULE_DIR/mx_mcp.ko $driver_dir/.
  depmod -a
fi

exit 0
